package wechat_v3

import (
	"duoke/model"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-pay/gopay"
	wechat3 "github.com/go-pay/gopay/wechat/v3"
	"io/ioutil"
)

var WechatPay = new(wxConfig)

type wxConfig struct {
}

func (c *Config) NewV3WxClient() (*wechat3.ClientV3, error) {
	privateKeyBytes, err := ioutil.ReadFile(c.PayKeyFilePath)
	if err != nil {
		return nil, err
	}
	privateKey := string(privateKeyBytes)
	client, err := wechat3.NewClientV3(c.PayMchId, c.PaySerialNo, c.PayKeyV3, privateKey)
	if err != nil {
		return nil, err
	}
	err = client.AutoVerifySign(true)
	return client, err
}

func (c *Config) Transfer(ctx *gin.Context, m *model.Transfer) (*wechat3.TransferBillsRsp, error) {
	client, err := c.NewV3WxClient()
	if err != nil {
		return nil, err
	}
	Bm := make(gopay.BodyMap)
	s := Bm.Set("appid", c.AppId).
		Set("out_bill_no", m.OutBillNo).
		Set("transfer_scene_id", m.TransferSceneId).
		Set("openid", m.Openid).
		Set("transfer_amount", m.TransferAmount).
		Set("transfer_remark", m.TransferRemark).
		Set("transfer_scene_report_infos", m.TransferSceneReportInfos).
		Set("notify_url", m.NotifyUrl)
	rsp, err := client.V3TransferBills(ctx, s)
	if rsp.Error != "" {
		return nil, errors.New(rsp.Error)
	}
	return rsp, nil
}
func (c *Config) CheckTransferBillsNotify(ctx *gin.Context) (*wechat3.V3DecryptTransferBillsResult, error) {
	// 解析微信回调通知
	notifyReq, err := wechat3.V3ParseNotify(ctx.Request)
	if err != nil {
		return nil, err
	}
	data := notifyReq.Resource
	result, err := wechat3.V3DecryptTransferBillsNotifyCipherText(data.Ciphertext, data.Nonce, data.AssociatedData, c.PayKeyV3)
	// 打印解密结果
	return result, err
}
